package com.ttbj.controller.salesman;


import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ttbj.api.dto.CompanyDto;
import com.ttbj.api.dto.Page;
import com.ttbj.api.dto.PermissionDto;
import com.ttbj.api.dto.SalesmanDto;
import com.ttbj.api.exception.BusinessException;
import com.ttbj.api.salesman.PermissionService;
import com.ttbj.api.salesman.SalesmanService;
import com.ttbj.constant.Const;
import com.ttbj.constant.PlatFormErrorCode;
import com.ttbj.constant.annotation.SystemControllerLog;
import com.ttbj.util.ViewDataUtil;


@Controller
public class SalesmanController {
	
	@Autowired
	private SalesmanService salesmanService;
	
	
	/**
     * 退出登录
     * @param request 请求对象
     * @return
     */
    @RequestMapping("/user/logout.htm")
    public String logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login";
    }
    
    /**
     * 跳转到用户列表
     * @return
     */
    @RequestMapping("/user/salesman_list.htm")
    public String salesman_list(Map<String, String> map) {
    	return "sysuser/sysuser_list";
    }
	
    /**
     * 修改密码页面
     * @return
     */
    @RequestMapping("/user/edit_password.htm")
    public String edit_password() {
    	return "sysuser/edit_password";
    }
    
    /**
     * 用户管理添加页面
     * @return
     */
  	 @RequestMapping("/user/edit_sysuser.htm")
  	 public String adduser(){
  		 return "sysuser/edit_sysuser";
  	 }
    
	/**登录
	 * @param request 请求对象
	 * @param username 用户名
	 * @param password 登录密码
	 * @return
	 */
	@RequestMapping(value = "/user/login.htm", method=RequestMethod.POST, produces = {"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	@SystemControllerLog(description="用户登录")
	public String login(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("password") String password) {
		try {
			if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			    return ViewDataUtil.buildFailureJson(PlatFormErrorCode.PARAM_IS_NULL.code(), "用户名或密码不能为空");
			}
			Subject subject = SecurityUtils.getSubject();
			//已经登录 跳转到首页
			if (subject.isAuthenticated()) {
			    return ViewDataUtil.buildSuccessJson("登录成功");
			}
			//身份验证
			subject.login(new UsernamePasswordToken(username, password.toCharArray()));
			final SalesmanDto authUserInfo = this.salesmanService.findRoleNameByName(username);
			request.getSession().setAttribute("userInfo", authUserInfo);
			return ViewDataUtil.buildSuccessJson("登录成功");
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			return ViewDataUtil.buildFailureJson(PlatFormErrorCode.USERNAME_OR_PASSWORD_ERROR.code(), "用户或密码错误");
		}
	}
	
    /**
     * 分页查询所有的用户
     * @param request
     * @param page 分页
     * @param salesman 封装查询条件的用户对象
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/getAllSalesmanUser.htm", produces={"text/html;charset=UTF-8;","application/json;"})
    public String getAllSalesmanUser(HttpServletRequest request, Page page, SalesmanDto salesman, String companyName) {
    	try {
			//当前登录用户
			SalesmanDto salesmanDto = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
			//设置公司编号，如果编号为null，则查询全部
			salesman.setSalesmanComnum(salesmanDto.getSalesmanComnum());
			if (StringUtils.isNotBlank(companyName)) {
				//设置公司名称，用于条件查询
				CompanyDto cDto = new CompanyDto();
				cDto.setComnumName(companyName);
				salesman.setCompanyDto(cDto);
			}
			//查询用户
			List<SalesmanDto> salesmanDtos =  this.salesmanService.findAllSalesmanByPage(page, salesman);
			int count = 0;
			if (null != salesmanDtos) {
			    count = this.salesmanService.findAllSalesmanByPageCount(salesman);
			}
			return ViewDataUtil.buildSuccessPageJson("用户", salesmanDtos, count);
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
    }
    
    /**
     * 查询用户名是否使用
     * @param fieldId 
     * @param fieldValue
     * @return 
     */
    @RequestMapping(value="/user/getSalesmanNameCheck.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
    @ResponseBody
    public String getSalesmanNameCheck(@RequestParam String fieldId, @RequestParam String fieldValue) {
    	boolean flag = true;
    	Object[] objects = new Object[2];
    	objects[0] = fieldId;
    	int count = this.salesmanService.findSalesmanByName(fieldValue);
    	//如果count 大于0，则说明已经存在
    	if (count > 0) {
			flag = false;
		}
    	objects[1] = flag;
    	//返回的内容为：[String,Boolean] String是接收到的fieldId的值。Boolean，验证通过返回true，不通过返回false
    	String result = "[\"" + objects[0] + "\"," + objects[1] + "]";
    	return result;
    }
    
    /**
     * 添加用户
     * @param request
     * @param salesmanDto
     * @return
     */
    @RequestMapping(value="/user/addToSalesmanInfo.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
    @ResponseBody
    @SystemControllerLog(description="增加用户")
    public String addToSalesmanInfo(HttpServletRequest request, SalesmanDto salesmanDto) {
    	try {
    		//当前登录用户
    		SalesmanDto currentSalesman = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
    		//获取登录用户的公司
    		String currentComnum = currentSalesman.getSalesmanComnum();
    		//如果为null，说明是主公司登录
    		if (null == currentComnum) {
    			//获取超管选择的公司
				String selectComnum = salesmanDto.getSalesmanComnum();
				//设置公司编号为选择的，如果不选择公司，则表示增加主公司的人员
				salesmanDto.setSalesmanComnum(selectComnum);
			}else {	//否则为企业登录，直接将登录用户的公司编号赋值
				salesmanDto.setSalesmanComnum(currentComnum);
			}
			this.salesmanService.addSalesman(salesmanDto);
			return ViewDataUtil.buildSuccessJson("添加用户成功");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
    }
    
    /**
     * 回显用户信息，去掉密码属性
     * @param request 
     * @param salesmanId 用户id
     * @return
     */
    @RequestMapping(value="/user/getSalesmanInfoById.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
    @ResponseBody
    public String getSalesmanInfoById(HttpServletRequest request, @RequestParam Long salesmanId) {
    	SalesmanDto salesmanDto = this.salesmanService.querySalesmanById(salesmanId);
    	salesmanDto.setSalesmanPwd("");
    	return ViewDataUtil.buildSuccessJson("用户信息", salesmanDto);
    }
    
    
   /**
    * 修改用户
    * @param request
    * @param salesmanDto
    * @return
    */
   @RequestMapping(value="/user/modifySalesmanInfo.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
   @ResponseBody
   @SystemControllerLog(description="修改用户信息")
   public String modifySalesmanInfo(SalesmanDto salesmanDto) {
	   try {
		   this.salesmanService.editSalesmanInfo(salesmanDto);
		   return ViewDataUtil.buildSuccessJson("修改用户成功");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
   }
   
   /**
    * 禁用和启用用户状态
    * @param request
    * @param salesmanId 用户id
    * @param isDel 是否删除的标识
    * @return
    */
   @RequestMapping(value="/user/delSalesmanInfo.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
   @ResponseBody
   @SystemControllerLog(description="禁用或启用用户状态")
   public String delSalesmanInfo(@RequestParam Long salesmanId, @RequestParam Integer isDel) {
	   try {
		   this.salesmanService.deleSalesmanById(salesmanId, isDel);
		   return ViewDataUtil.buildSuccessJson("用户状态改变成功");
		} catch (BusinessException e) {
			return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
		}
   }
   
   /**
    * 修改密码
    * @param request
    * @param inputPassword 输入的密码
    * @param newPassword 输入的新密码
    * @return
    */
   @RequestMapping(value="/user/modifySalesmanPwd.htm", method=RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;"})
   @ResponseBody
   public String modifySalesmanPwd(HttpServletRequest request, @RequestParam String inputPassword, @RequestParam String newPassword) {
	 try {
		 //当前登录用户
		 SalesmanDto currentSalesman = (SalesmanDto) request.getSession().getAttribute(Const.TTBJ_USER_SESSION_KEY);
		 //获取密码
		 String salesmanPwd = currentSalesman.getSalesmanPwd();
		 //获取用户id
		 Long salesmanId = currentSalesman.getSalesmanId();
		 //获取用户名
		 String salesmanName = currentSalesman.getSalesmanName();
		 //执行密码修改
		 this.salesmanService.editSalesmanPwd(inputPassword, salesmanPwd, salesmanName, salesmanId, newPassword);
		 return ViewDataUtil.buildSuccessJson("修改密码成功!");
	 } catch (BusinessException e) {
		return ViewDataUtil.buildFailureJson(e.getErrorCode(), e.getMessage());
	 }
   }
   
   /**
    * 查询未删除的开单人员的id，名字和分站点名
    * @param request
    * @return
    */
   @RequestMapping(value="/user/getSalesmanIdNameCompany.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
   @ResponseBody
   public String getSalesmanIdNameCompany(HttpServletRequest request) {
	   List<SalesmanDto> salesmanDtos = this.salesmanService.findSalesmanIdNameCompany();
	   return ViewDataUtil.buildSuccessJson("业务员列表", salesmanDtos);
   }
}
